// 蜂窝蜜造平台生成代码，此文件只生成一次，不需要添加到 .beeignore

package com.fowo.api.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fowo.api.controller.purchase.vo.WarehouseBinParam;
import com.fowo.api.controller.purchase.vo.warehouseBinInventory;
import com.fowo.api.entity.FBAInvoice;
import com.fowo.api.entity.FbaShipment;
import com.fowo.api.entity.ListingFather;
import com.fowo.api.entity.WarehouseBin;
import com.fowo.api.mapper.WarehouseBinDMapper;
import com.fowo.api.model.fbainvoice.FBAInvoiceItemVo;
import com.fowo.api.model.fbainvoice.FBAInvoiceSearchParamPo;
import com.fowo.api.model.fbainvoice.FBAInvoiceVo;
import com.fowo.api.model.fbainvoice.detail.FBAInvoiceDetailItemVo;
import com.fowo.api.model.fbainvoice.detail.FBAInvoiceDetailItemVoPages;
import com.fowo.api.model.fbainvoice.detail.FBAInvoiceDetailSearchParamPo;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.entity.SysUser;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.service.SysUserService;
import com.fowo.api.sys.service.impl.SysUserServiceImpl;
import com.fowo.api.user.model.JwtUserInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 发货单 服务实现类
 */
@Service
public class FBAInvoiceServiceImpl extends FBAInvoiceBaseServiceImpl {

    @Resource
    private SysUserServiceImpl sysUserService;
    @Resource
    private WarehouseBinDMapper warehouseBinDMapper;
    @Resource
    private WarehouseBinServiceImpl warehouseBinService;
    @Resource
    private ListingFatherServiceImpl listingFatherService;

    @Resource
    private  FbaShipmentServiceImpl fbaShipmentService;
    public Long create2(FBAInvoiceVo model) throws Exception {
        model.setInvoiceStatus("10");
        Long aLong = super.create(model);
        return aLong;
    }
    @DataActivity(action = SysDataActivityAction.Add)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long create(FBAInvoiceVo model) throws Exception {
        //设置释放锁库村islockinventory
        String shipmentCode = model.getInvoiceDetailList().get(0).getShipmentCode();
        model.getInvoiceDetailList().forEach(x->{
            if( x.getShipmentShopFnsku()!=null){
                if(StringUtils.isNumeric(x.getShipmentShopFnsku())){
                    ListingFather byId = listingFatherService.getById(x.getShipmentShopFnsku());
                    x.setShipmentShopFnsku(byId.getFnsku());
                }

            }
        });
        model.setIslockinventory("0");
        JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
        Long userId = jwtUserInfo.getUserId();
        SysUser byId = sysUserService.getById(userId);
        if(model.getLxCreateUser()==null){
            model.setLxCreateUser(byId.getName());
            if(shipmentCode!=null){
                model.setShipmentCode(shipmentCode);
            }
        }

        FbaShipment one = fbaShipmentService.getOne(Wrappers.<FbaShipment>query().lambda().eq(FbaShipment::getShipmentId, shipmentCode));
        if(one!=null){
            model.setShipmentIds(one.getId());
        }
        Long l = super.create(model);
        FBAInvoiceVo voById = super.getVoById(l);
        //货件关联发货单
//        FbaShipment one = fbaShipmentService.getOne(Wrappers.<FbaShipment>query().lambda().eq(FbaShipment::getShipmentId, shipmentCode));
        if(one!=null){
//            Assert.isNull(one.getInvoiceNo(),"已生成发货单:"+one.getInvoiceNo());
            Assert.isTrue((!one.getShipmentStatus().equals("cancelled"))&&(!one.getShipmentStatus().equals("delete")),"状态为Delete和Cancel的货件不支持生成发货单");
            one.setInvoiceNo(voById.getInoviceCode());
            fbaShipmentService.updateById(one);
        }
//        setBin(voById);
        return  l;
    }


    private void setBin(FBAInvoiceVo voById) throws Exception {
        List<FBAInvoiceDetailItemVo> invoiceDetailList = voById.getInvoiceDetailList();
        for(int i=0;i<invoiceDetailList.size();i++){
            FBAInvoiceDetailItemVo fbaInvoiceDetailItemVo = invoiceDetailList.get(i);
            if(fbaInvoiceDetailItemVo.getOutBingId()!=null){
                continue;
            }
            WarehouseBinParam search=new WarehouseBinParam();
            search.setWarehouseId(voById.getDeliveryWarehouse());
            if(fbaInvoiceDetailItemVo.getShipmentShop()!=null){
                search.setShopId(Long.valueOf(fbaInvoiceDetailItemVo.getShipmentShop()));
            }
            search.setFnskuName(fbaInvoiceDetailItemVo.getShipmentShopFnsku());
            search.setProductId(fbaInvoiceDetailItemVo.getName());
            List<warehouseBinInventory> wareBinOne = warehouseBinDMapper.getWareBinOne(search);
            if(wareBinOne.size()>0){
                warehouseBinInventory warehouseBinInventory = wareBinOne.get(0);
                fbaInvoiceDetailItemVo.setOutBingId(Long.valueOf(warehouseBinInventory.getId()));
                fbaInvoiceDetailItemVo.setWhbCode(warehouseBinInventory.getStorageBin());
            }else{
                WarehouseBin zancun = warehouseBinService.getOne(Wrappers.<WarehouseBin>query()
                        .lambda().eq(WarehouseBin::getStorageBin, "可用暂存")
                        .eq(WarehouseBin::getWarehouseId, voById.getDeliveryWarehouse()));
                fbaInvoiceDetailItemVo.setOutBingId(Long.valueOf(zancun.getId()));
                fbaInvoiceDetailItemVo.setWhbCode(zancun.getStorageBin());
            }

        }
        super.update(voById);
    }
    @Transactional(rollbackFor = Exception.class)
    public Long create4(FBAInvoiceVo model)throws Exception {
        model.setInvoiceStatus("30");//10 待配货 30待发货 40已发货 50已作废
        Long aLong = super.create(model);
        //锁库存
        super.locksInventory(aLong);
        super.lockpInventory(aLong);
        return aLong;
    }
    @Override
    protected Page<?> appendWithChild(
            Page<FBAInvoiceItemVo> pageResult,
            String sort
    ){
        Page<?> page = super.appendWithChild(pageResult, sort);
        List<?> records = page.getRecords();
        for(int i=0;i<records.size();i++){
            JSONObject o = (JSONObject)records.get(i);
            Page<FBAInvoiceDetailItemVoPages> invoiceDetailList =(Page<FBAInvoiceDetailItemVoPages>) o.get("invoiceDetailList");
            String jsonString = JSON.toJSONString(invoiceDetailList.getRecords());
            o.put("productitems", jsonString);
//            o.put("productitems", o.get("invoiceDetailList"));
        }
        return page;
    }
    /**
     * 删除发货单
     * @param id 发货单的主键
     * @return 删除是否成功
     */
    @DataActivity(action = SysDataActivityAction.Del)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delete(Long id) throws Exception {
        FBAInvoice byId = this.getById(id);
        //先吧锁定的库存还回来
        if(byId.getIslockinventory().equals("1")){
            byId.setInvoiceStatus("30");
            boolean update =super.updateById(byId);
            //释放锁库存
            super.cancelLocksInventory(id);
            super.cancelLockpInventory(id);
        }
        batchDeleteChilds(Collections.singletonList(id));
        updateShipment(byId);
        return this.removeById(id);
    }
    //货件修改为""
    public   void updateShipment(FBAInvoice voById){
        String shipmentCode = voById.getShipmentCode();
        FbaShipment one = fbaShipmentService.getOne(Wrappers.<FbaShipment>query().lambda().eq(FbaShipment::getShipmentId, shipmentCode));
        if(one!=null){
            LambdaUpdateWrapper<FbaShipment> lambdaUpdate = Wrappers.lambdaUpdate();
            lambdaUpdate.eq(FbaShipment::getId, one.getId());
            lambdaUpdate.set(FbaShipment::getInvoiceNo, null);
            fbaShipmentService.update(one,lambdaUpdate);
        }

    }


    @Override
    public Page<FBAInvoiceItemVo> fBAInvoiceAllViewPage(
            FBAInvoiceSearchParamPo search
    ) {
        return AddData(super.fBAInvoiceAllViewPage(search));
    }

    @Override
    public Page<FBAInvoiceItemVo> fBAInvoiceDistributedViewPage(
            FBAInvoiceSearchParamPo search
    ) {
        return AddData(super.fBAInvoiceDistributedViewPage(search));
    }

    @Override
    public Page<FBAInvoiceItemVo> fBAInvoiceSendViewPage(
            FBAInvoiceSearchParamPo search
    ) {
        return AddData(super.fBAInvoiceSendViewPage(search));
    }

    @Override
    public Page<FBAInvoiceItemVo> fBAInvoiceHasSendViewPage(
            FBAInvoiceSearchParamPo search
    ) {
        return AddData(super.fBAInvoiceHasSendViewPage(search));
    }
    @Override
    public Page<FBAInvoiceItemVo> fBAInvoiceCancelViewPage(
            FBAInvoiceSearchParamPo search
    ) {
        return AddData(super.fBAInvoiceCancelViewPage(search));
    }

    Page<FBAInvoiceItemVo> AddData(Page<FBAInvoiceItemVo> search){
//        search.getRecords().forEach(item->{
//            FBAInvoiceDetailSearchParamPo invoiceDetailListSearchParamPo =
//                    new FBAInvoiceDetailSearchParamPo();
//            invoiceDetailListSearchParamPo.setParentFBAInvoice(item.getId());
//            invoiceDetailListSearchParamPo.applySqlSegments();
//            List<FBAInvoiceDetailItemVo> search1 = fBAInvoiceDetailService.search(invoiceDetailListSearchParamPo);
//            String jsonString = JSON.toJSONString(search1);
//            item.setProductitems(jsonString);
//        });
        return search;
    }

}
